%% Preliminary
clear;clc;
load('Results_IntDegreeAdjCost.mat');

%% Collect the IRFs
MatSize     =   size(SOLUTION);
IRFs        =   cell(size(SOLUTION));
for ii=1:prod(MatSize)
    [rr,cc]         =   ind2sub(MatSize,ii);
    IRFs{rr,cc}     =   SubFun_CollectIRF(SOLUTION{rr,cc});
end
save('IRFs.mat','IRFs','-v7.3');

%% Collect the results
MatSize     =   size(IRFs);
KeyResults  =   cell(size(IRFs));
for ii=1:prod(MatSize)
    [rr,cc]         =   ind2sub(MatSize,ii);
    KeyResults{ii}  =   SubFun_KeyResults(IRFs{rr,cc});
end
save('KeyResults.mat','KeyResults');

%% Plots

%--------------------------------------------------------------------------
% Setup
%--------------------------------------------------------------------------
List_Prob_ext   =   (0.10:0.1:0.90)';
Num_Prob_ext    =   length(List_Prob_ext);

List_Fin_AdjCost=   [0.01,0.05,0.1,0.2,0.4,0.8,2,5,10,50,100,1000];
Num_Fin_AdjCost =   length(List_Fin_AdjCost);
XAxis       =   log(List_Fin_AdjCost)-log(0.8);
YAxis       =   List_Prob_ext;

VarInfo     =   struct('C_Agg_M_ext',[1,2],'C_dom_M_ext',[2,2],'C_ext_M_ext',[3,2],...
                       'DevUIP_M_ext',[4,2],...
                       'C_Std_M_ext',[5,2],'C_GapByFinInt_M_ext',[7,2],...
                       'EffReturn_M_ext',[9,2],...
                       'C_Agg_Y_H',[1,3],'C_dom_Y_H',[2,3],'C_ext_Y_H',[3,3],...
                       'DevUIP_Y_H',[4,3],...
                       'C_Std_Y_H',[5,3],'C_GapByFinInt_Y_H',[7,3],...
                       'EffReturn_Y_H',[9,3]);
VarList     =   fieldnames(VarInfo);

set(groot,'defaulttextinterpreter','Latex');  
set(groot, 'defaultAxesTickLabelInterpreter','Latex');  
set(groot, 'defaultLegendInterpreter','Latex'); 

fig_size    =   [1,1].*[1,0.75]*1/2;
fig_gap     =   [0.02,0.02];
fig_VMargin =   [0.15,0.02];
fig_HMargin =   [0.12,0.02]; 

fig_SubPlot =   @(ii_vv)subtightplot(1,1,ii_vv,fig_gap,fig_VMargin,fig_HMargin);


% Figure
for ii=1:length(VarList)
    vv      =   VarList{ii};
    Ind_Data=   VarInfo.(vv);
    
    Fig     =   FigureSetup(vv,fig_size);
    ax      =   fig_SubPlot(1);
    ZAxis   =   zeros(size(KeyResults));
    for rr=1:size(ZAxis,1)
        for cc=1:size(ZAxis,2)
            ZAxis(rr,cc)    =   KeyResults{rr,cc}(Ind_Data(1),Ind_Data(2));
        end
    end

    ColorMap=   Graph_ColorMap(ZAxis);

    ax = surf(XAxis,YAxis,ZAxis);
    xlim([min(XAxis),max(XAxis)]);
    ylim([min(YAxis),max(YAxis)]);
    % xticks(XAxis);yticks(List_Prob_ext);
    xticklabels(round(exp(xticks+log(0.8)),1));
    % yticklabels(List_Prob_ext);
    xlabel('Portfolio adjustment cost');
    ylabel('Share of fin-integrated hhs');
    colormap(ColorMap);
%     colorbar;

    view(3);

    print('-depsc','-r1000',Fig,['TableGraphs/HeatMap_',vv]);
% close(Fig);

end
